package com.adolph.netty.nettydemo;

import com.adolph.netty.dto.MessageObj;
import com.alibaba.fastjson.JSON;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * 〈功能概述〉<br>
 *
 * @author: wangxiangjun
 * @date: 2020-10-09 9:29
 */

public class NettyServerHandler extends ChannelInboundHandlerAdapter {




    /**
     * 读取信息
     * @Author wangxiangjun
     * @Date 9:34 2020-10-09
     * @param ctx 上下文信息，含有管道、通道、地址
     * @param msg
     * @return void
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("NettyServerHandler被调用======1");
        //如果业务处理耗时较长，异步处理任务
        //解决方案：1、用户自定义普通任务，提交到NIOEventLoop的TaskQueue中
//        ctx.channel().eventLoop().execute(()->{
//            System.out.println("处理耗时任务！");
//        });
//        //2、提交到scheduleTaskQueue中
//        ctx.channel().eventLoop().schedule(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        },20, TimeUnit.SECONDS);
//
//
//        System.out.println("===========" + ctx);

//        System.out.println("客户端信息====="+byteBuf.toString(CharsetUtil.UTF_8));
//        System.out.println("客户端地址====="+ctx.channel().remoteAddress());

        if(msg instanceof MessageObj){
            System.out.println("NettyServerHandler接收消息：====="+ JSON.toJSONString(msg));
        }else{
            ByteBuf byteBuf = (ByteBuf) msg;
            String tempStr = byteBuf.toString(CharsetUtil.UTF_8);
            System.out.println("NettyServerHandler接收消息：====="+tempStr);
            tempStr =tempStr + "==1==";
            byteBuf.writeBytes(tempStr.getBytes(CharsetUtil.UTF_8));
            //调用下一个ChannelHandler的ChannelRead
            ctx.fireChannelRead(msg);
        }


//        ctx.write(msg);
    }

    //数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //数据写入缓存并刷新
        //ctx.writeAndFlush(Unpooled.copiedBuffer("服务端发送消息",CharsetUtil.UTF_8));
    }

    //异常处理，关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyServerHandler===========channelInactive");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("NettyServerHandler===========channelActive");
    }
}
